var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/questionnaire');
const fs = require('fs')
var qr = require('qr-image');
const cors = require("cors")
const model = require("./models")


app.use(session({
    secret: 'questionnaire',
    cookie: {
        maxAge: 1000 * 60 * 60 * 3
    },
    store: new MongoStore({
        url: 'mongodb://localhost/questionnaire',
        collection: 'sessions'
    }),
    resave: true,
    saveUninitialized: false
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'view')));
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cors())
app.use(bodyParser.json());
// app.use(questionmaires())



var Questionnaire = require('./controllers/questionnaire');
var Question = require('./controllers/question');
var Option = require('./controllers/option');
var Answer = require('./controllers/answer');
var Admin = require('./controllers/admin');


app.get('/', Admin.homePage);
app.get('/manage/login', Admin.loginPage);
app.post('/manage/login', Admin.login);
app.get('/manage/logout/', Admin.loginRequired, Admin.logout);
app.get('/manage', Admin.loginRequired, Questionnaire.listPage);
app.get('/manage/questionnaire/add', Admin.loginRequired, Questionnaire.addPage);
app.post('/manage/questionnaire/add', Admin.loginRequired, Questionnaire.add);
app.post('/manage/questionnaire/edit', Admin.loginRequired, Questionnaire.edit);
app.post('/manage/questionnaire/publish', Admin.loginRequired, Questionnaire.publish);
app.get('/manage/questionnaire/:questionnaire', Admin.loginRequired, Questionnaire.editPage);
app.get('/manage/questions', Admin.loginRequired, Question.listPage);
app.get('/manage/question/add', Admin.loginRequired, Question.addPage);
app.get('/manage/question/:question', Admin.loginRequired, Question.editPage);
app.post('/manage/question/add', Admin.loginRequired, Question.add);
app.get('/data/questionnaires', Admin.loginRequired, Questionnaire.list);
app.get('/data/questionnaire/:questionnaire', Admin.loginRequired, Questionnaire.detail);
app.get('/data/questions', Admin.loginRequired, Question.list);
app.get('/data/question/:question', Admin.loginRequired, Question.detail);
app.post('/data/question/:question', Admin.loginRequired, Question.edit);
app.delete('/data/questionnaire/:questionnaire', Admin.loginRequired, Questionnaire.delete);
app.delete('/data/question/:question', Admin.loginRequired, Question.delete);
app.delete('/data/option/:option', Admin.loginRequired, Option.delete);

app.get('/questionnaire/:questionnaire', Answer.indexPage);
app.post('/questionnaire/:questionnaire', Answer.submit);
app.get('/user/questionnaire/:questionnaire', Answer.questionnaireData);
app.get('/result/:questionnaire', Answer.resultPage);
app.get('/statistics/:questionnaire', Answer.statistics);



app.get("/index", (req, res) => {
    // console.log('登录成功跳转',fs.readFileSync('./view/manage/index.html', 'utf-8'));
    res.send(fs.readFileSync('./view/manage/index.html', 'utf-8'))
})









app.get("/", (req, res) => {
    model.conn(function (db) {
        db.collection("users").find().toArray((err, docs) => {
            if (err) {
                console.log(err)
                return;
            }
            console.log(docs)
            res.send(fs.readFileSync('./login.html', 'utf-8'))
        })
    })
})












// 登录

app.post("/login", (req, res) => {
    let login_data = {
        username: req.body.username,
        password: req.body.password
    }
    let questionnaire = req.params.questionnaire
    req.session.questionnaire = questionnaire
    console.log(questionnaire);
    console.log(req.session.questionnaire);
    // 首先根据用户输入的内容去查询
    model.conn(function (db) {


        db.collection("users").findOne({
            newusername: login_data.username,
            newpassword: login_data.password
        }, (err, ret) => {

            if (err) {
                res.send({
                    code: 400,
                    msg: "用户登录失败"
                })
            }

            let login_ret_re = ret || {}


            if (login_ret_re.newusername && login_ret_re.newpassword) {

                req.session.user = login_ret_re.newusername

                if (req.session.user === "xiaoyou") {

                    res.send({
                        code: 200,
                        msg: "登录成功"
                    })
                } else if (req.session.user === "") {
                    res.send({
                        code: 202,
                        msg: "请登录！"
                    })
                } else if (!req.session.user) {
                    res.send({
                        code: 204,
                        msg: "请登录！！"
                    })
                } else {
                    res.send({
                        code: 201,
                        msg: "普通用户！"
                    })
                }
            } else {
                res.send({
                    code: 203,
                    msg: "用户或者密码错误"
                })
            }
        })
    })

})







// 注册

app.post("/register", (req, res) => {
    let data = {
        newusername: req.body.newusername,
        newpassword: req.body.newpassword,
    }

    console.log(data);
    model.conn(function (db) {
        db.collection("users").findOne({
            newusername: data.newusername
        }, (err, ret) => {
            if (err) {
                console.log("查询失败")
                res.send({
                    code: 400,
                    msg: '用户注册失败,请重试'
                })
            }
            let ret_re = ret || {}
            if (ret_re.newusername) {
                console.log("该用户名已存在")
                res.send({
                    code: 201,
                    msg: "该用户名已存在"
                })
                return
            } else {
                model.conn(function (db) {
                    db.collection("users").insertOne(data, (err, ret_1) => {
                        if (err) {
                            console.log(err)
                            res.send({
                                code: 400,
                                msg: '用户注册失败,请重试'
                            })
                        }
                        let ret_re_1 = ret_1 || {}
                        if (ret_re_1.insertedCount == 1) {
                            res.send({
                                code: 200,
                                msg: "注册成功"
                            })
                        } else {
                            res.send({
                                code: 400,
                                msg: "注册失败"
                            })
                        }

                    })
                })
            }
        })
    })
})

















app.get('/a', (req, res) => {
    res.send(fs.readFileSync('./fengxiang.html', 'utf-8'))
})



//拦截路由


app.use(function (req, res, next) {
    var url = req.originalUrl;//获取浏览器中当前访问的nodejs路由地址；
    var userCookies=req.session.user; //获取客户端存取的cookie,userCookies为cookie的名称；
//有时拿不到cookie值，可能是因为拦截器位置放错，获取该cookie的方式是依赖于nodejs自带的cookie模块，
//因此，获取cookie必须在1,2步之后才能使用，否则拿到的cookie就是undefined.
    console.log("123"+url);
    console.log("app获得cookie"+req.session.user+"真假11111："+(req.session.user==undefined));
 
    if(url=='/login'&&!(userCookies==undefined)){ //通过判断控制用户登录后不能访问登录页面；
        return res.redirect('/');//页面重定向；
    }
    next();
});


app.get('/Code/:code', (req, res) => {
    let text = `http://127.0.0.1:8081//questionnaire/${req.params.code}`;
    let svg_string = qr.image(text, {
        type: 'png'
    });
    res.status = 200
    // res.type='image/png'
    // res.setHeader('Content-type','image/png')
    // res.send(svg_string);

    res.type('png')
    svg_string.pipe(res)

})

app.get('/fx/:id', (req, res) => {
    let id = req.params
    console.log(id);
    res.send(fs.readFileSync('./view/manage/fengxiang.html', 'utf-8'))
})










app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.send(err.message);
});









var port = 8081;

app.listen(port);

console.log("http://127.0.0.1:8081");





